<template>
  <div class="todo-page">
    <div class="todo-header">
      <button class="back-button" @click="$router.push('/')">← 返回首页</button>
      <h1>待办事项</h1>
    </div>
    
    <!-- 新增：居中容器，限制最大宽度750px -->
    <div class="centered-container">
      <!-- 添加待办事项区域 -->
      <div class="add-todo">
        <n-input
          v-model:value="newTodoText"
          placeholder="输入新的待办事项..."
          @keyup.enter="addTodo"
          class="todo-input"
        />
        <n-button type="primary" @click="addTodo">添加</n-button>
      </div>
      
      <!-- 新增：筛选工具栏 -->
      <div class="todo-toolbar">
        <div class="filters">
          <n-button 
            type="text" 
            :primary="filter === 'all'" 
            @click="filter = 'all'"
          >
            全部
          </n-button>
          <n-button 
            type="text" 
            :primary="filter === 'active'" 
            @click="filter = 'active'"
          >
            未完成
          </n-button>
          <n-button 
            type="text" 
            :primary="filter === 'completed'" 
            @click="filter = 'completed'"
          >
            已完成
          </n-button>
        </div>
        <n-button 
          type="text" 
          danger 
          @click="clearCompleted"
          :disabled="!hasCompletedTodos"
        >
          清除已完成
        </n-button>
      </div>
      
      <!-- 待办事项列表 -->
      <div class="todo-list">
        <n-list bordered>
          <n-list-item 
            v-for="todo in filteredTodos" 
            :key="todo.id"
            class="todo-item"
            :class="{ 'completed': todo.completed }"
          >
            <!-- 支持双击编辑 -->
            <div class="todo-content" @dblclick="enterEditMode(todo.id)">
              <n-checkbox 
                v-model:checked="todo.completed" 
                @change="toggleTodo(todo.id)"
              />
              <!-- 编辑模式切换 -->
              <span 
                class="todo-text" 
                v-if="!todo.isEditing"
              >
                {{ todo.text }}
              </span>
              <n-input
                v-else
                v-model:value="todo.editText"
                @keyup.enter="saveEdit(todo.id)"
                @blur="saveEdit(todo.id)"
                ref="editInput"
                class="edit-input"
              />
            </div>
            <n-button 
              type="text" 
              danger 
              size="small" 
              @click="deleteTodo(todo.id)"
            >
              删除
            </n-button>
          </n-list-item>
          
          <n-empty v-if="filteredTodos.length === 0" description="暂无待办事项" />
        </n-list>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
import { NInput, NButton, NList, NListItem, NCheckbox, NEmpty } from 'naive-ui';

// 待办事项状态
const newTodoText = ref('');
const todos = ref([]);
// 新增：筛选状态（all/active/completed）
const filter = ref('all');
// 编辑状态相关
const editInput = ref(null);

// 从本地存储加载待办事项
const loadTodos = () => {
  const saved = localStorage.getItem('todos');
  if (saved) {
    todos.value = JSON.parse(saved).map(todo => ({
      ...todo,
      isEditing: false, // 新增：编辑状态标记
      editText: todo.text // 新增：编辑文本缓存
    }));
  }
};

// 保存待办事项到本地存储
const saveTodos = () => {
  localStorage.setItem('todos', JSON.stringify(todos.value));
};

// 新增：筛选后的待办事项
const filteredTodos = computed(() => {
  switch (filter.value) {
    case 'active':
      return todos.value.filter(todo => !todo.completed);
    case 'completed':
      return todos.value.filter(todo => todo.completed);
    default:
      return todos.value;
  }
});

// 新增：是否有已完成的待办事项
const hasCompletedTodos = computed(() => {
  return todos.value.some(todo => todo.completed);
});

// 添加待办事项
const addTodo = () => {
  if (!newTodoText.value.trim()) return;
  
  todos.value.push({
    id: Date.now(),
    text: newTodoText.value.trim(),
    completed: false,
    isEditing: false,
    editText: ''
  });
  
  newTodoText.value = '';
  saveTodos();
};

// 切换待办事项完成状态
const toggleTodo = (id) => {
  const todo = todos.value.find(t => t.id === id);
  if (todo) {
    todo.completed = !todo.completed;
    saveTodos();
  }
};

// 删除待办事项
const deleteTodo = (id) => {
  todos.value = todos.value.filter(todo => todo.id !== id);
  saveTodos();
};

// 新增：清除所有已完成待办事项
const clearCompleted = () => {
  todos.value = todos.value.filter(todo => !todo.completed);
  saveTodos();
};

// 新增：进入编辑模式
const enterEditMode = (id) => {
  const todo = todos.value.find(t => t.id === id);
  if (todo) {
    todo.isEditing = true;
    todo.editText = todo.text; // 初始化编辑文本
    nextTick(() => {
      editInput.value?.focus(); // 自动聚焦编辑框
    });
  }
};

// 新增：保存编辑
const saveEdit = (id) => {
  const todo = todos.value.find(t => t.id === id);
  if (todo) {
    todo.text = todo.editText.trim() || todo.text; // 防止空文本
    todo.isEditing = false;
    saveTodos();
  }
};

// 组件挂载时加载数据
onMounted(loadTodos);
// 组件卸载时保存数据
onUnmounted(saveTodos);
</script>

<style scoped>
/* 新增：主题色变量（便于统一调整） */
:root {
  --primary-color: #646cff; /* 主色调（与倒计时页面保持一致） */
  --primary-light: #8389ff;
  --danger-color: #ff4d4f;
  --text-primary: #333;
  --text-secondary: #666;
  --text-disabled: #999;
  --bg-light: #f5f7ff;
  --border-color: #e0e0e0;
  --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 页面背景优化 */
.todo-page {
  height: 100vh;
  padding: 2rem;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  background-color: #f9fafb; /* 浅灰背景，提升层次感 */
}

/* 标题样式优化 */
.todo-header h1 {
  color: var(--primary-color);
  font-weight: 600;
  letter-spacing: 0.5px;
}

/* 返回按钮美化 */
.back-button {
  padding: 0.5rem 1rem;
  background-color: white;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.back-button:hover {
  background-color: var(--bg-light);
  border-color: var(--primary-light);
  color: var(--primary-color);
}

/* 居中容器阴影效果 */
.centered-container {
  max-width: 750px;
  width: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  padding: 0 1rem;
}

/* 添加待办区域优化 */
.add-todo {
  display: flex;
  gap: 0.8rem;
  width: 100%;
  padding: 1rem;
  background-color: white;
  border-radius: 10px;
  box-shadow: var(--shadow-sm);
}

.todo-input {
  flex: 1;
  height: 48px; /* 统一高度 */
  border-radius: 8px;
  border: 1px solid var(--border-color);
  transition: all 0.2s;
}

.todo-input:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(100, 108, 255, 0.1);
}

.add-todo .n-button {
  height: 48px;
  padding: 0 1.5rem;
  border-radius: 8px;
  font-weight: 500;
}

/* 工具栏按钮样式优化 */
.todo-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.8rem 1rem;
  background-color: white;
  border-radius: 10px;
  box-shadow: var(--shadow-sm);
}

.filters .n-button {
  padding: 0.4rem 0.8rem;
  border-radius: 20px; /* 圆角按钮 */
  transition: all 0.2s;
}

.filters .n-button--primary {
  background-color: var(--primary-color);
  color: white;
}

.filters .n-button:not(.n-button--primary):hover {
  background-color: var(--bg-light);
  color: var(--primary-color);
}

/* 新增：筛选工具栏样式 */
.todo-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 0;
}

.filters {
  display: flex;
  gap: 0.5rem;
}

/* 列表容器美化 */
.todo-list {
  flex: 1;
  overflow-y: auto;
  max-height: calc(100vh - 300px);
  background-color: white;
  border-radius: 10px;
  box-shadow: var(--shadow-sm);
}

/* 列表项样式优化 */
.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.2rem;
  transition: all 0.2s;
  border-bottom: 1px solid var(--border-color);
}

.todo-item:last-child {
  border-bottom: none;
}

.todo-item:hover {
  background-color: var(--bg-light);
}

/* 待办文本样式 */
.todo-text {
  font-size: 1.1rem;
  color: var(--text-primary);
  transition: all 0.2s;
  line-height: 1.5;
}

/* 已完成样式增强 */
.completed .todo-text {
  text-decoration: line-through;
  color: var(--text-disabled);
  font-style: italic; /* 斜体增强区分 */
}

/* 复选框美化 */
.todo-content .n-checkbox {
  transform: scale(1.2); /* 放大复选框 */
  margin-right: 0.8rem;
}

/* 删除按钮交互 */
.todo-item .n-button--danger {
  opacity: 0.6;
  transition: all 0.2s;
}

.todo-item:hover .n-button--danger {
  opacity: 1; /* 悬停时显示完整颜色 */
}

/* 编辑模式样式 */
.edit-input {
  width: 300px;
  margin: 0 0.5rem;
  border: 1px solid var(--primary-color);
  border-radius: 6px;
  padding: 0.5rem;
  box-shadow: 0 0 0 2px rgba(100, 108, 255, 0.1);
}

/* 滚动条样式 */
.todo-list::-webkit-scrollbar {
  width: 8px;
}

.todo-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.todo-list::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 10px;
}

.todo-list::-webkit-scrollbar-thumb:hover {
  background: #aaa;
}

/* 空状态样式优化 */
.n-empty {
  padding: 3rem 0;
}

.n-empty .n-empty__description {
  color: var(--text-secondary);
  font-size: 1rem;
}

/* 响应式细节调整 */
@media (max-width: 768px) {
  .todo-toolbar {
    flex-direction: column;
    align-items: stretch;
    gap: 0.8rem;
    padding: 1rem;
  }
  
  .edit-input {
    width: 100%;
  }
  
  .todo-item {
    padding: 0.8rem 1rem;
  }
}
</style>
